package com.zgm.ch04._5_1;

import java.security.MessageDigest;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class MessageDigestDemo {

	public static void main(String[] args){
		XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/zgm/ch04/_5_1/_5_1-context.xml"));
		/*注意：当调用bactory.getBean("sha")时，spring将使用MessageDigestFactoryBean的getObject()
		 * 方法返回一个MessgaeDigest实例
		 * 
		 */
		MessageDigest d1 = (MessageDigest) factory.getBean("sha");
		MessageDigest d2 = (MessageDigest) factory.getBean("md5");
		
		calculateDigest("Hello world", d1);
		calculateDigest("Hello world", d2);
		
	}
	
	public static void calculateDigest(String message, MessageDigest digest){
		System.out.println("Digest using " + digest.getAlgorithm() + ":");
		
		digest.reset();
		final byte[] bytes = digest.digest(message.getBytes());
		
		for(byte b : bytes){
//			System.out.print(b);
			System.out.print(String.format("%02x", b));
		}
		
		System.out.println("");
	}
}
